package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	ps "lab-service/proto/security"
	pu "lab-service/proto/user"
	"net/http"
)

type Account struct {
	UserClient     pu.UserService
	SecurityClient ps.SecurityService
}

func (a *Account) Login(ctx *gin.Context) {
	form := new(LoginForm)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	userRsp, err := a.UserClient.Login(ctx, &pu.UserRequest{
		Email:    form.Email,
		UserName: form.UserName,
		Password: form.Password,
		Phone:    form.Phone,
	})
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	jwtRsp, err := a.SecurityClient.SignJwt(ctx, &ps.SecurityRequest{
		Uid:      userRsp.Uid,
		Remember: form.Remember,
	})
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, err)
		return
	}

	ctx.JSON(http.StatusOK, jwtRsp)
}

func (a *Account) Register(ctx *gin.Context) {
	form := new(RegForm)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	// do register a new user
	userRsp, err := a.UserClient.Register(context.Background(), &pu.UserRequest{
		Email:    form.Email,
		UserName: form.UserName,
		Password: form.Password,
		Phone:    form.Phone,
	})
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	// sign a new jwt token
	jwtRsp, err := a.SecurityClient.SignJwt(ctx, &ps.SecurityRequest{
		Uid: userRsp.Uid,
	})
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, err)
		return
	}

	ctx.JSON(http.StatusOK, jwtRsp)
}
